from django.shortcuts import render, redirect, reverse
from django.contrib.auth import authenticate, login as auth_login, logout as auth_logout
from django.contrib.auth.models import User
def index(request):
    # 使用 Django 的会话来获取当前登录的用户
    return render(request, 'index.html', {'user': request.user})
def register(request):
    if request.method == 'GET':
        return render(request, 'register.html')
    elif request.method == 'POST':
        uname = request.POST['uname']
        passwd = request.POST['passwd']
        age = request.POST['age']
        
        # 检查用户名是否已存在
        if User.objects.filter(username=uname).exists():
            return render(request, 'register.html', {'error': '用户名已存在'})

        # 创建新用户
        user = User.objects.create_user(username=uname, password=passwd)
        user.age = age  # 确保 User 模型有 age 字段
        user.save()

        # 注册成功后跳转到登录页面
        return redirect(reverse('user:login'))  # 正确的重定向到登录页面

def login(request):
    if request.method == 'POST':
        uname = request.POST['uname']
        passwd = request.POST['passwd']
        user = authenticate(request, username=uname, password=passwd)
        if user is not None:
            auth_login(request, user)  # 使用 Django 的 login 函数
            return redirect(reverse('user:index'))  # 重定向到用户主页
        else:
            return render(request, 'login.html', {'error': '用户名或密码错误'})
    else:
        return render(request, 'login.html')

def logout(request):
    auth_logout(request)  # 使用 Django 的 logout 函数
    return redirect(reverse('user:login'))  # 重定向到登录页面
